package com.bruce.starts.demo.commonerror.io;

import cn.hutool.core.util.HexUtil;
import com.google.common.base.Charsets;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author luotuan
 * @Description
 * @create 2021-05-11 17:20
 **/
@Slf4j
public class FileBadEncodingIssue {
    public static void main(String[] args) throws IOException {
        init();
        wrong();
        right1();
        right2();
    }
    public static void init() throws IOException {
        Files.deleteIfExists(Paths.get("hello.txt"));
        Files.write(Paths.get("hello.txt"),"你好hi".getBytes(Charset.forName("GBK")));
        log.info("bytes:{}", HexUtil.encodeHexStr(Files.readAllBytes(Paths.get("hello.txt"))).toUpperCase());
    }

    private static void wrong() throws IOException {
        log.info("charset: {}", Charset.defaultCharset());

        char[] chars = new char[10];
        String content = "";
        try (FileReader fileReader = new FileReader("hello.txt")) {
            int count;
            while ((count = fileReader.read(chars)) != -1) {
                content += new String(chars, 0, count);
            }
        }
        log.info("result:{}", content);

        Files.write(Paths.get("hello2.txt"), "你好hi".getBytes(Charsets.UTF_8));
        log.info("bytes:{}", HexUtil.encodeHexStr(Files.readAllBytes(Paths.get("hello2.txt"))).toUpperCase());

    }

    private static void right1() throws IOException{
        char[] chars = new char[10];
        String context = "";
        try(FileInputStream fileInputStream = new FileInputStream("hello.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,Charset.forName("GBK"))){
            int count;
            while ((count = inputStreamReader.read(chars))!=-1){
                context+=new String(chars,0,count);
            }
        }
        log.info("result:{}",context);
    }

    private static void right2() throws IOException{
        log.info("result:{}",Files.readAllLines(Paths.get("hello.txt"),Charset.forName("GBK")).stream().findFirst().orElse(""));
    }
}
